<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isLogin ? $t('auth.loginTitle') : $t('auth.registerTitle')"
    width="500px"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="auth-dialog">
      <!-- 登录表单 -->
      <LoginForm 
        v-if="isLogin" 
        @switch-mode="switchToRegister"
        @open-terms="openTermsDialog"
        @login-success="handleLoginSuccess"
      />
      
      <!-- 注册表单 -->
      <RegisterForm 
        v-else 
        @switch-mode="switchToLogin"
        @open-terms="openTermsDialog"
      />
    </div>
    
    <!-- 条款和协议弹窗 -->
    <TermsDialog
      v-model="termsDialogVisible"
      :terms-type="termsType"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import LoginForm from './LoginForm.vue';
import RegisterForm from './RegisterForm.vue';
import TermsDialog from './TermsDialog.vue';

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: 'login',
    validator: (value: string) => ['login', 'register'].includes(value)
  }
});

const emit = defineEmits(['update:modelValue', 'update:mode']);

// 控制弹窗显示
const dialogVisible = ref(props.modelValue);

// 当前模式：登录或注册
const isLogin = ref(props.mode === 'login');

// 条款弹窗控制
const termsDialogVisible = ref(false);
const termsType = ref('privacy');

// 监听props.modelValue变化
watch(() => props.modelValue, (newVal) => {
  dialogVisible.value = newVal;
});

// 监听dialogVisible变化
watch(() => dialogVisible.value, (newVal) => {
  emit('update:modelValue', newVal);
});

// 监听props.mode变化
watch(() => props.mode, (newVal) => {
  isLogin.value = newVal === 'login';
});

// 切换到注册模式
const switchToRegister = () => {
  isLogin.value = false;
  emit('update:mode', 'register');
};

// 切换到登录模式
const switchToLogin = () => {
  isLogin.value = true;
  emit('update:mode', 'login');
};

// 打开条款弹窗
const openTermsDialog = (type: string) => {
  termsType.value = type;
  termsDialogVisible.value = true;
};

// 处理登录成功事件
const handleLoginSuccess = () => {
  dialogVisible.value = false;
};

// 暴露方法给父组件
defineExpose({
  openTermsDialog
});
</script>

<style scoped lang="scss">
.auth-dialog {
  padding: 10px 26px;
}
</style>